package org.lyq.erp;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class }) // 阻止spring自动注入DataSource bean
@EnableTransactionManagement // 开启数据事务管理
public class DataSourceConfiguration {

	// 创建事务管理器
	@Bean(name = "txManager1")
	public PlatformTransactionManager txManager(DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}

	@Bean(name = "dataSource"/* ,destroyMethod = "close" */) // destroyMethod = "close"连接空闲时去关闭连接
	@Qualifier(value = "dataSource") // 限定描述符除了能根据名字进行注入，但能进行更细粒度的控制如何选择候选者
	@Primary // 用@Primary区分主数据源
	@ConfigurationProperties(prefix = "c3p0")
	public DataSource dataSource() {

		return DataSourceBuilder.create().type(com.mchange.v2.c3p0.ComboPooledDataSource.class).build();
	}
}